import axios from 'axios';
import qs from 'qs';
import untils from '../assets/untils/untils';

const Axios = axios.create({
  baseURL: '/',
  timeout: 30000,
  responseType: 'json',
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  }
});
const CancelToken = axios.CancelToken;
const requestMap = new Map();
let _token = untils.getLocalStorage('token') || '';
let userPlatform = untils.getPlatform() || '';
let _randomcode = untils.getRandomCode();  //随机码
let _signature = untils.getSignature(_randomcode);   //签名
let osName = untils.getPlatform();
let source='/fwAdd';
// 请求前置拦截器
Axios.interceptors.request.use(
  config => {
    // 防重复提交
    const keyString = qs.stringify(Object.assign({}, {url: config.url, method: config.method}, config.data));
    // if (requestMap.get(keyString)) {
    //   // 取消当前请求
    //   config.cancelToken = new CancelToken((cancel) => {
    //     cancel('Please slow down a little');
    //   });
    // }
    requestMap.set(keyString, true);
    Object.assign(config, {_keyString: keyString});

    let stringify=config.headers.stringify;
    if(stringify==''||stringify==undefined||stringify){
      if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
        // 序列化
        config.data = qs.stringify(config.data);
      }
    }
    return config;
  },
  error => {
    untils.closeLoading();
    return Promise.reject(error);
  }
);

// 返回响应拦截器
Axios.interceptors.response.use(
  res => {
    untils.closeLoading();
    // 重置requestMap
    // const config: any = res.config;
    // requestMap.set(config._keyString, false);

    if (res.status === 200) {
      return res.data;
    } else {
      let resText = untils.getErrorRes(res);

    }
    // todo 弹窗提示等
    console.log(`request error：${res}`);
  },
  error => {
    untils.closeLoading();
    // let resText = untils.getErrorRes(error.response.status);
    // untils.Alert({
    //   html: resText
    // });
    return {
      code: -1
    };
  }
);

/**
 * @description
 * 请求
 * @param params
 */

const request = (params) => {
  //是否显示loading
  params.showLoading && untils.showLoading();
  return Axios({
    url: params.url,
    data: params.data,
    params: params.params,
    method: params.method || "POST",
    timeout: params.timeout || 30000,
    responseType: 'json',
    withCredentials: true,
    // application/json;charset=utf-8
    headers: {
      'system': userPlatform,
      'randomcode': _randomcode,
      'signature': _signature,
      "System-Name": "app-pad-recruitment",
      "version": "1.0.0",
      "osname": osName,
      "agentcode": untils.getLocalStorage('userInfo', true).id || '',
      "token": _token || '',
      'Content-Type': params.contentType || "application/x-www-form-urlencoded;charset=utf-8",
      'stringify':params.stringify
    }

  });

};
export default {request};




